#!/bin/bash

appName=notesync

opt=$1
if [ "-help" == "$opt" -o "-h" == "$opt" ]; then
    echo "usage: sh $0 os_type version"
    echo "os_type: linux_amd64, linux_arm64"
    echo "example: sh $0 linux_arm64 v1.0.0"
    exit 0
fi

#check os type
os_type=$1
if [ "$os_type" == "" ];then
    arch_type=amd64
    isX86=`cat /proc/version | grep x86_64`
    isAMD=`cat /proc/version | grep amd64`
    if [ "$isX86" == "" ] && [ "$isAMD" == "" ];then
        arch_type=arm64
    fi
elif [ "$os_type" == "linux_amd64" ];then
    arch_type=amd64
elif [ "$os_type" == "linux_arm64" ];then
    arch_type=arm64
fi

echo "arch_type: $arch_type"

version=v1.0.0
if [ -n "$2" ]; then
    version=$2
fi

# GIT_SHA=`git rev-parse --short HEAD || echo`
# buildAt=`date "+%Y-%m-%dT%H:%M:%S"`
# echo "start build  $appName $version $GIT_SHA"
echo "start build  $appName $version"

# build
# CGO_ENABLED=0 GOOS=darwin GOARCH=$arch_type go build  -ldflags "-X main.Version=${version} -X main.GitSHA=${GIT_SHA} -X main.BuildAt=${buildAt}" -o ${appName} -mod=vendor
cmd=`printf "CGO_ENABLED=0 GOOS=$GOOS GOARCH=$arch_type go build  -o ${appName} -mod=vendor"`
echo "start build $appName, cmd: $cmd"
echo "$cmd" | bash

# cp and pack tar
dest=${appName}_$version
mkdir -p $dest/{conf,bin}


\cp -rf ../conf/config.toml $dest/conf
\cp -rf $appName $dest/bin
#\cp -rf $GOPATH/bin/sign $dest/bin
\cp -rf start.sh $dest/bin
\cp -rf stop.sh $dest/bin
\cp -rf install.sh $dest
echo $version > $dest/version.info
tar -czvf $dest.tar.gz $dest

# delete other
rm -rf $appName
rm -rf $dest

echo "build $appName $version succeed"
